package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.model.mongo.ReceiveSounds;
import com.tanhua.model.mongo.Sound;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Circle;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

@DubboService
public class SoundApiImpl implements SoundApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;

    /**
     * 保存语音
     *
     * @param sound
     * @return
     */
    @Override
    public String save(Sound sound) {
        sound.setSid(idWorker.getNextId("sound"));
        mongoTemplate.save(sound);
        return sound.getId().toHexString();
    }

    /**
     * 查询一条语音
     * @return
     */
    @Override
    public Sound findOne() {
        Query query = Query.query(Criteria.where("receiveState").is(0)).with(Sort.by(Sort.Order.desc("created")));
        Sound sound = mongoTemplate.findOne(query, Sound.class);
        if (sound==null){
           return null;
        }
        Query query1 = Query.query(Criteria.where("_id").is(sound.getId()));
        Update update = Update.update("receiveState", 1);
        mongoTemplate.updateFirst(query,update,Sound.class);
        return sound;
    }

    /**
     * 查询当日已获取次数
     * @param userId
     * @param date
     * @return
     */
    @Override
    public Integer count(Long userId, String date) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("date").is(Long.valueOf(date)));
        long count = mongoTemplate.count(query, ReceiveSounds.class);
        return Integer.parseInt(String.valueOf(count));
    }
}
